package com.morgan.basemodule.utils

import android.os.Handler
import android.os.Looper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.asExecutor

/**
 *description：线程工作
 *<br>author：caowugao
 *<br>time：2021/4/2 0002 17:27
 */
class ThreadWorker private constructor(){

    private val mainHandler : Handler by lazy {Handler(Looper.getMainLooper())}

    class Holder private constructor(){
        companion object {
            val INSTANCE = ThreadWorker()
        }
    }

    companion object {
        fun getInstance() = Holder.INSTANCE
    }

    fun runOnMain(task : Runnable) {
        if (Looper.getMainLooper() == Looper.myLooper()) {
            task.run()
            return
        }
        mainHandler.post(task)
    }

    fun runOnMainDelay(task : Runnable, delay : Long) {
        mainHandler.postDelayed(task, delay)
    }

    fun runOnIO(task: Runnable) {
        Dispatchers.IO.asExecutor().execute(task)
    }

    fun runOnIODelay(task : Runnable, delay : Long) {
        mainHandler.postDelayed({
            runOnIO(task)
        }, delay)
    }
}